import time
import sqlite3
from datetime import datetime

def process_raw_value(value, data_type):
    """处理原始值，确保类型正确并处理空值"""
    if value is None:
        # 根据数据类型返回默认值
        if data_type == int:
            return 0
        elif data_type == float:
            return 0.0
        elif data_type == bool:
            return False
        else:
            return None
    
    try:
        # 类型转换
        if data_type == bool:
            # 处理各种布尔表示形式
            if isinstance(value, str):
                return value.lower() in ['true', '1', 'yes', 'on']
            return bool(value)
        else:
            return data_type(value)
    except (ValueError, TypeError):
        # 转换失败时返回默认值
        if data_type == int:
            return 0
        elif data_type == float:
            return 0.0
        elif data_type == bool:
            return False
        return None

# 物模型到字段的映射（包含数据类型）
PROPERTY_MAPPING = {
    # Spark设备上报的属性
    'radar_heartrate': ('heart_rate', int),
    'radar_breath': ('breath_rate', int),
    'radar_body_exist': ('body_exist', bool),
    'sleep_state': ('sleep_state', int),
    'radar_sleep_score': ('sleep_score', int),
    'temp': ('temperature', int),
    'humidity': ('humidity', int),
    'brightness': ('brightness', int),
    'dB': ('noise_level', int),
    'sleepflag': ('sleep_flag', int),
    'heartrate': ('heart_rate_secondary', int),
    'body_movement': ('body_movement', int),
    'LightSwitch': ('light_switch', bool),
    'sleep_wake_hour': ('wake_hours', float),
    'sleep_light_hour': ('light_sleep_hours', float),
    'sleep_deep_hour': ('deep_sleep_hours', float),
    'servoangle': ('servo_angle', int),
    'servospeed': ('servo_speed', int),
    'heat': ('heat_level', int),
    'pose': ('pose', int),
    'sleeping': ('sleeping', bool),
    'turn_over': ('turn_over', int),
    
    # Monitor设备专属属性
    'sitting_up': ('sitting_up', bool)
}

class EnhancedDataProcessor:
    """增强型数据处理器 - 严格处理空值和数据验证"""
    
    def __init__(self):
        self.device_data = {
            'spark': {},
            'monitor': {}
        }
        self.processed_data = {}
        self.last_update = 0
    
    def update_device_data(self, device_name, raw_data):
        """更新设备原始数据"""
        # 只接受spark和monitor设备
        if device_name not in ['spark', 'monitor']:
            print(f"⚠️ 未知设备: {device_name}")
            return
        
        # 存储原始数据
        if raw_data:
            self.device_data[device_name] = raw_data
            self.last_update = time.time()
            print(f"📊 {device_name}设备数据已更新: {len(raw_data)} 个属性")
        
        # 处理数据
        self._process_data()
    
    def _process_data(self):
        """处理并聚合多设备数据"""
        processed = {}
        
        # 处理Spark设备数据
        spark_data = self.device_data.get('spark', {})
        for prop_id, (field_name, data_type) in PROPERTY_MAPPING.items():
            # 跳过Monitor专属属性
            if prop_id == 'sitting_up':
                continue
                
            # 获取原始值并处理
            raw_value = spark_data.get(prop_id)
            processed[field_name] = process_raw_value(raw_value, data_type)
        
        # 处理Monitor设备数据
        monitor_data = self.device_data.get('monitor', {})
        if 'sitting_up' in PROPERTY_MAPPING:
            field_name, data_type = PROPERTY_MAPPING['sitting_up']
            raw_value = monitor_data.get('sitting_up')
            processed[field_name] = process_raw_value(raw_value, data_type)
        
        # 添加时间戳
        processed['timestamp'] = self.last_update if self.last_update > 0 else time.time()
        
        # 数据验证
        self._validate_data(processed)
        
        # 存储处理后的数据
        self.processed_data = processed
    
    def _validate_data(self, data):
        """数据验证与修正"""
        validation_rules = {
            'heart_rate': (40, 180, "心率"),
            'breath_rate': (8, 40, "呼吸率"), 
            'temperature': (10, 40, "温度"),
            'humidity': (0, 100, "湿度"),
            'brightness': (0, 1000, "亮度"),
            'noise_level': (0, 120, "噪音"),
            'servo_angle': (0, 90, "舵机角度"),
            'servo_speed': (0, 100, "舵机速度"),
            'heat_level': (0, 10, "加热等级"),
            'sleep_score': (0, 100, "睡眠评分"),
            'sleep_state': (0, 5, "睡眠状态"),
            'pose': (0, 10, "姿态"),
            'turn_over': (0, 100, "翻身次数"),
            'body_movement': (0, 100, "体动次数")
        }
        
        for field, (min_val, max_val, name) in validation_rules.items():
            if field in data and data[field] is not None:
                if not min_val <= data[field] <= max_val:
                    print(f"⚠️ {name}异常: {data[field]} (正常范围: {min_val}-{max_val})，重置为0")
                    data[field] = 0
    
    def get_processed_data(self):
        """获取处理后的数据"""
        return self.processed_data.copy()
    
    def get_categorized_data(self):
        """获取分类数据"""
        data = self.get_processed_data()
        
        return {
            'vitals': {
                'heart_rate': data.get('heart_rate', 0),
                'breath_rate': data.get('breath_rate', 0),
                'body_exist': data.get('body_exist', False),
                'sleep_state': data.get('sleep_state', 0),
                'sleep_score': data.get('sleep_score', 0),
                'body_movement': data.get('body_movement', 0),
                'pose': data.get('pose', 0),
                'sleeping': data.get('sleeping', False),
                'turn_over': data.get('turn_over', 0),
                'sitting_up': data.get('sitting_up', False),
            },
            'environment': {
                'temperature': data.get('temperature', 0),
                'humidity': data.get('humidity', 0),
                'brightness': data.get('brightness', 0),
                'noise_level': data.get('noise_level', 0),
                'light_switch': data.get('light_switch', False),
            },
            'bed_status': {
                'servo_angle': data.get('servo_angle', 0),
                'servo_speed': data.get('servo_speed', 0),
                'heat_level': data.get('heat_level', 0),
            },
            'sleep_analysis': {
                'wake_hours': data.get('wake_hours', 0.0),
                'light_sleep_hours': data.get('light_sleep_hours', 0.0),
                'deep_sleep_hours': data.get('deep_sleep_hours', 0.0),
                'sleep_flag': data.get('sleep_flag', 0),
            },
            'timestamp': data.get('timestamp', time.time())
        }

class DataStorage:
    """数据存储模块 - SQLite数据库"""
    
    def __init__(self, db_name='health_bed_data.db'):
        self.db_name = db_name
        self._create_table()
    
    def _get_connection(self):
        """获取数据库连接"""
        return sqlite3.connect(self.db_name)
    
    def _create_table(self):
        """创建数据表"""
        with self._get_connection() as conn:
            cursor = conn.cursor()
            cursor.execute('''
            CREATE TABLE IF NOT EXISTS device_data (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                timestamp REAL NOT NULL,
                heart_rate INTEGER DEFAULT 0,
                breath_rate INTEGER DEFAULT 0,
                body_exist BOOLEAN DEFAULT 0,
                sleep_state INTEGER DEFAULT 0,
                sleep_score INTEGER DEFAULT 0,
                temperature INTEGER DEFAULT 0,
                humidity INTEGER DEFAULT 0,
                brightness INTEGER DEFAULT 0,
                noise_level INTEGER DEFAULT 0,
                sleep_flag INTEGER DEFAULT 0,
                heart_rate_secondary INTEGER DEFAULT 0,
                body_movement INTEGER DEFAULT 0,
                light_switch BOOLEAN DEFAULT 0,
                wake_hours REAL DEFAULT 0.0,
                light_sleep_hours REAL DEFAULT 0.0,
                deep_sleep_hours REAL DEFAULT 0.0,
                servo_angle INTEGER DEFAULT 0,
                servo_speed INTEGER DEFAULT 0,
                heat_level INTEGER DEFAULT 0,
                sitting_up BOOLEAN DEFAULT 0,
                pose INTEGER DEFAULT 0,
                sleeping BOOLEAN DEFAULT 0,
                turn_over INTEGER DEFAULT 0,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
            )
            ''')
            conn.commit()
            print("✅ 数据库表已创建/验证")
    
    def save_data(self, data):
        """保存处理后的数据"""
        try:
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute('''
                INSERT INTO device_data (
                    timestamp, heart_rate, breath_rate, body_exist, sleep_state, 
                    sleep_score, temperature, humidity, brightness, noise_level,
                    sleep_flag, heart_rate_secondary, body_movement, light_switch,
                    wake_hours, light_sleep_hours, deep_sleep_hours, servo_angle,
                    servo_speed, heat_level, sitting_up, pose, sleeping, turn_over
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
                ''', (
                    data.get('timestamp', time.time()),
                    data.get('heart_rate', 0),
                    data.get('breath_rate', 0),
                    data.get('body_exist', False),
                    data.get('sleep_state', 0),
                    data.get('sleep_score', 0),
                    data.get('temperature', 0),
                    data.get('humidity', 0),
                    data.get('brightness', 0),
                    data.get('noise_level', 0),
                    data.get('sleep_flag', 0),
                    data.get('heart_rate_secondary', 0),
                    data.get('body_movement', 0),
                    data.get('light_switch', False),
                    data.get('wake_hours', 0.0),
                    data.get('light_sleep_hours', 0.0),
                    data.get('deep_sleep_hours', 0.0),
                    data.get('servo_angle', 0),
                    data.get('servo_speed', 0),
                    data.get('heat_level', 0),
                    data.get('sitting_up', False),
                    data.get('pose', 0),
                    data.get('sleeping', False),
                    data.get('turn_over', 0)
                ))
                conn.commit()
                return True
        except Exception as e:
            print(f"❌ 数据存储失败: {e}")
            return False
    
    def get_latest_data(self, limit=1):
        """获取最新数据"""
        try:
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute('''
                SELECT * FROM device_data 
                ORDER BY timestamp DESC 
                LIMIT ?
                ''', (limit,))
                return cursor.fetchall()
        except Exception as e:
            print(f"❌ 数据查询失败: {e}")
            return []
    
    def get_statistics(self):
        """获取数据统计信息"""
        try:
            with self._get_connection() as conn:
                cursor = conn.cursor()
                cursor.execute('''
                SELECT 
                    COUNT(*) as total_records,
                    AVG(heart_rate) as avg_heart_rate,
                    AVG(breath_rate) as avg_breath_rate,
                    AVG(temperature) as avg_temperature,
                    MAX(timestamp) as latest_timestamp
                FROM device_data
                WHERE heart_rate > 0
                ''')
                return cursor.fetchone()
        except Exception as e:
            print(f"❌ 统计查询失败: {e}")
            return None

if __name__ == "__main__":
    # 测试数据处理器
    print("🧪 测试增强型数据处理器")
    
    processor = EnhancedDataProcessor()
    storage = DataStorage()
    
    # 测试空值处理
    print("\n📊 测试空值处理")
    test_data = {
        'radar_heartrate': None,
        'temp': None,
        'sitting_up': None
    }
    processor.update_device_data('spark', test_data)
    processor.update_device_data('monitor', {'sitting_up': None})
    
    result = processor.get_processed_data()
    print(f"空值处理结果: heart_rate={result.get('heart_rate')}, temperature={result.get('temperature')}, sitting_up={result.get('sitting_up')}")
    
    # 测试数据验证
    print("\n🔍 测试数据验证")
    invalid_data = {
        'radar_heartrate': 300,  # 超出正常范围
        'temp': -10,             # 超出正常范围
        'humidity': 150          # 超出正常范围
    }
    processor.update_device_data('spark', invalid_data)
    
    result = processor.get_processed_data()
    print(f"验证后结果: heart_rate={result.get('heart_rate')}, temperature={result.get('temperature')}, humidity={result.get('humidity')}")
    
    # 测试数据存储
    print("\n💾 测试数据存储")
    success = storage.save_data(result)
    print(f"数据存储: {'✅ 成功' if success else '❌ 失败'}")
    
    # 查看统计信息
    stats = storage.get_statistics()
    if stats and stats[1] is not None:
        print(f"数据库统计: 总记录数={stats[0]}, 平均心率={stats[1]:.1f}")
    else:
        print("数据库统计: 暂无有效心率数据")
    
    print("\n✅ 测试完成!")
